/**$Licence:
 *   Use this however/wherever you like, just don't blame me if it breaks anything.
 *   Copyright (C) 2008 - 2012 xingsheng.zhu@gmail.com All rights reserved.
 */
package com.blazemina.config;

import java.io.IOException;
import java.net.URL;

import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * @author JackChu
 * @version 1.0.0 2012-1-4 下午4:31:03
 */
public class XMLConfig {

	private Digester digester;

	protected String[] registrations = {
			"-//Blazemina Foundation//DTD Blazemina Configuration 1.0//EN",
			"/com/blazemina/config/blazemina-config_1_0.dtd" };

	public XMLConfig() {
	}

	public void initDegister() {
		digester = new Digester();
		digester.setValidating(false);
		digester.addRuleSet(new ConfigRuleSet());

		for (int i = 0; i < registrations.length; i += 2) {
			URL url = this.getClass().getResource(registrations[i + 1]);
			if (url != null) {
				digester.register(registrations[i], url.toString());
			}
		}
		//digester.push(new BlazeminaConfig());
	}

	public BlazeminaConfig parse(URL url) {
		BlazeminaConfig config = null;
		try {
			config = (BlazeminaConfig)digester.parse(url);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXParseException e) {
			throw new XmlParseException("Line " + e.getLineNumber()
					+ " in XML file from " + url + " is invalid", e);
		} catch (SAXException e) {
			e.printStackTrace();
		}
		return config;
	}

}
